
import Head from 'next/head'

<Head>
  <script>
    {
      `(function() {
         var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?e60fb290e204e04c5cb6f79b0ac1e697";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
       })();`
    }
  </script>
</Head>

![LangChain](https://pica.zhimg.com/50/v2-56e8bbb52aa271012541c1fe1ceb11a2_r.gif)




Replicate
=============================


> 
> [Replicate](https://replicate.com/blog/machine-learning-needs-better-tools)在云端运行机器学习模型。我们拥有一系列开源模型，只需几行代码即可运行。如果您正在构建自己的机器学习模型，Replicate可以轻松实现大规模部署。
> 
> 
> 

这个例子介绍了如何使用LangChain与`Replicate` [模型](https://replicate.com/explore)进行交互。

设置[#](#setup "永久链接到此标题")
------------------------

要运行此教程电脑，您需要创建一个[Replicate](https://replicate.com)账户并安装[replicate python客户端](https://github.com/replicate/replicate-python)。

```python
!pip install replicate

```

```python
# get a token: https://replicate.com/account

from getpass import getpass

REPLICATE_API_TOKEN = getpass()

```

```python
 ········

```

```python
import os

os.environ["REPLICATE_API_TOKEN"] = REPLICATE_API_TOKEN

```

```python
from langchain.llms import Replicate
from langchain import PromptTemplate, LLMChain

```

调用模型[#](#calling-a-model "永久链接到此标题")
------------------------------------

在[复制探索页面（replicate explore page）](https://replicate.com/explore)上找到一个模型，然后按照`model_name/version`的格式将模型名称和版本粘贴在此处。

例如，对于此[dolly模型](https://replicate.com/replicate/dolly-v2-12b)，点击API选项卡。模型名称/版本将是：`replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5`。

只需要`model`参数，但是我们可以在初始化时添加其他模型参数。

例如，如果我们运行稳定扩散并想要更改图像尺寸：

```python
Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf", input={'image_dimensions': '512x512'})

```

*请注意，模型仅返回第一个输出。* 

```python
llm = Replicate(model="replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5")

```

```python
prompt = """
Answer the following yes/no question by reasoning step by step. 
Can a dog drive a car?
"""
llm(prompt)

```

```python
'The legal driving age of dogs is 2. Cars are designed for humans to drive. Therefore, the final answer is yes.'

```

我们可以使用此语法调用任何复制模型。例如，我们可以调用stable-diffusion。

```python
text2image = Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf", 
                       input={'image_dimensions': '512x512'})

```

```python
image_output = text2image("A cat riding a motorcycle by Picasso")
image_output

```

```python
'https://replicate.delivery/pbxt/Cf07B1zqzFQLOSBQcKG7m9beE74wf7kuip5W9VxHJFembefKE/out-0.png'

```

该模型会输出一个URL。让我们将其呈现出来。

```python
from PIL import Image
import requests
from io import BytesIO

response = requests.get(image_output)
img = Image.open(BytesIO(response.content))

img

```


链式 Chaining Calls[#](#chaining-calls "Permalink to this headline")
---------------------------------------------------------------

Langchain的整个重点在于...链式！这里有一个示例，说明如何做到这一点。

```python
from langchain.chains import SimpleSequentialChain

```
首先，让我们将这个模型的LLM定义为flan-5，将text2image定义为stable-diffusion。
```python
dolly_llm = Replicate(model="replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5")
text2image = Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf")

```

链中的第一个提示

```python
prompt = PromptTemplate(
    input_variables=["product"],
    template="What is a good name for a company that makes {product}?",
)

chain = LLMChain(llm=dolly_llm, prompt=prompt)

```

链中的第二个提示，获得公司描述的logo。

```python
second_prompt = PromptTemplate(
    input_variables=["company_name"],
    template="Write a description of a logo for this company: {company_name}",
)
chain_two = LLMChain(llm=dolly_llm, prompt=second_prompt)

```

第三个提示，根据第二个提示输出的描述来创建图片

```python
third_prompt = PromptTemplate(
    input_variables=["company_logo_description"],
    template="{company_logo_description}",
)
chain_three = LLMChain(llm=text2image, prompt=third_prompt)

```

现在让我们运行它！

```python
# Run the chain specifying only the input variable for the first chain.
overall_chain = SimpleSequentialChain(chains=[chain, chain_two, chain_three], verbose=True)
catchphrase = overall_chain.run("colorful socks")
print(catchphrase)

```

```python
> Entering new SimpleSequentialChain chain...
novelty socks
todd & co.
https://replicate.delivery/pbxt/BedAP1PPBwXFfkmeD7xDygXO4BcvApp1uvWOwUdHM4tcQfvCB/out-0.png

> Finished chain.
https://replicate.delivery/pbxt/BedAP1PPBwXFfkmeD7xDygXO4BcvApp1uvWOwUdHM4tcQfvCB/out-0.png

```

```python
response = requests.get("https://replicate.delivery/pbxt/eq6foRJngThCAEBqse3nL3Km2MBfLnWQNd0Hy2SQRo2LuprCB/out-0.png")
img = Image.open(BytesIO(response.content))
img

```


